package com.mmd.base.hander;

import cn.hutool.extra.spring.SpringUtil;
import com.mmd.base.annotation.AnonymousAccess;
import com.mmd.base.auth.UserContextHolder;
import com.mmd.base.auth.UserInfoVerify;
import com.mmd.base.exception.ApplicationException;
import com.mmd.base.pojo.entity.UserInfo;
import com.mmd.core.enums.LoginEnum;
import com.mmd.core.enums.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Slf4j
@Component
public class AuthorizationHandler extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("HandlerInterceptorAdapter拦截器执行");
        if (!(handler instanceof HandlerMethod)) return true;
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(AnonymousAccess.class)) {
            AnonymousAccess annotation = method.getAnnotation(AnonymousAccess.class);
            if(annotation != null){
                log.info("HandlerInterceptorAdapter拦截器匿名执行");
                return super.preHandle(request,response,handler);
            }
        }
        LoginEnum loginEnum = UserContextHolder.loginEnum(request);
        if (loginEnum.getValue().equals(LoginEnum.MER.getValue())) {

        }

        // 当有双Authorization时关比Security匿名访问 否则因匿名后的url在获取上下文会无法获取用户信息UserContextHolder.getSecurityContextHolder()
        // {@link SecurityConfig#configure()}关比
        UserInfo<Object> userInfo = UserContextHolder.getSecurityContextHolder();
        log.info("HandlerInterceptorAdapter拦截器获取到用户信息{}",userInfo);
        Assert.notNull(userInfo,ResultEnum.LOGIN.getMessage());
        try{
            UserInfoVerify userInfoVerify = SpringUtil.getBean(UserInfoVerify.class);
            userInfoVerify.run(userInfo);
        } catch (NoSuchBeanDefinitionException e) {
            log.error(e.getMessage());
        }
        log.info("HandlerInterceptorAdapter拦截器执行完毕");
        return super.preHandle(request,response,handler);
    }
}
